package com.example.confirm;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//多条同步确认
public class MultipleSyncConfirm {

    private static final String MULTIPLE_SYNC_CONFIRM_EXCHANGE = "multipleSyncConfirmExchange";
    private static final String MULTIPLE_SYNC_CONFIRM_QUEUE = "multipleSyncConfirmQueue";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        if (true) {
            factory.setHost("localhost");
            factory.setPort(5672);
            factory.setUsername("guest");
            factory.setPassword("guest");
            factory.setVirtualHost("/");
        }
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //交换机声明
        channel.exchangeDeclare(MULTIPLE_SYNC_CONFIRM_EXCHANGE, BuiltinExchangeType.DIRECT, true);
        channel.queueDeclare(MULTIPLE_SYNC_CONFIRM_QUEUE,true,false,false,null);
        channel.queueBind(MULTIPLE_SYNC_CONFIRM_QUEUE,MULTIPLE_SYNC_CONFIRM_EXCHANGE,MULTIPLE_SYNC_CONFIRM_QUEUE);

        /**
         * 开启 confirm 确认
         */
        channel.confirmSelect();

        long begin = System.currentTimeMillis();//开始时间

        for (int i = 1; i <= 1000; i++) {
            String str = i + "";
            channel.basicPublish(MULTIPLE_SYNC_CONFIRM_EXCHANGE, MULTIPLE_SYNC_CONFIRM_QUEUE, null, str.getBytes());

            if (i % 100 == 0) {
                //生产者等待确认
                boolean b = channel.waitForConfirms();
                if (b) {
                    System.out.println("第 " + i + " 条发送成功");
                } else {
                    System.out.println("第 " + i + " 条发送失败================");
                }
            }
        }

        long end = System.currentTimeMillis();//结束时间
        System.out.println("总耗时: " + (end - begin) + " 毫秒");
    }


}
